package com.comments.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import com.alibaba.fastjson.JSONObject;
import com.angel.acv.pojo.ACv;
import com.angel.acv.pojo.ACvBasic;
import com.angel.acv.pojo.ACvEducation;
import com.angel.acv.pojo.ACvExpectation;
import com.angel.acv.pojo.ACvJob;
import com.angel.acv.pojo.ACvProject;
import com.angel.acv.pojo.ACvSkill;
import com.angel.base.utils.AngelObject;
import com.cvtech.pojo.EducationInfo;
import com.cvtech.pojo.ExperienceInfo;
import com.cvtech.pojo.ITSkills;
import com.cvtech.pojo.ProjectInfo;
import com.cvtech.pojo.ResumeInfo;
import com.zph.pojo.BasicDE;

/**
 * @DESC
 * @Author zhangzhenhua
 * @Date 2017年5月11日 下午4:29:27
 */
public class TransAngelObj {

	// 加载字典 省、市、区
	static String dic_city = "city_simple.txt";
	// static Map<String, Integer> provinces = null, citys = null, districts =
	// null;
	static List<String> provinces = null, citys = null, districts = null;
	static {
		try {
			// 读入字典
			InputStream in_city = Resources.getResourceAsStream(dic_city);
			BufferedReader br = new BufferedReader(new InputStreamReader(in_city, "utf-8"));
			String str = null;
			provinces = new ArrayList<String>();
			citys = new ArrayList<String>();
			districts = new ArrayList<String>();
			int i = 1;
			while ((str = br.readLine()) != null) {
				if (i < 35) { // 1 -34 省
					provinces.add(str);
				} else if (i < 375) {// 1 - 374 ⑩
					citys.add(str);
				} else { // 区、县
					districts.add(str);
				}
				i++;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public static void trans(ResumeInfo resume, AngelObject ao) {

		String uid = null;
		// 获取uid
		if (resume.getFilePojo() != null) {
			uid = getUid(resume.getFilePojo().getPath());// 与文件名同
		}

		if (uid == null || uid.equals("")) {
			uid = System.nanoTime() + ""; // 获取当前时间
		}
		ao.setUid(uid);
		// 主键表
		transCv(resume, ao);
		// 基本信息
		transBasic(resume, ao);
		// 教育经历
		transEdu(resume, ao);
		// 期望信息
		transExp(resume, ao);
		// 工作经历
		transJob(resume, ao);
		// 项目经历
		transPro(resume, ao);
		// 技能信息
		transSkill(resume, ao);

	}

	private static void transCv(ResumeInfo re, AngelObject ao) {
		ACv cv = new ACv();
		cv.setUid(ao.getUid());
		if (re.getFilePojo() != null)
			cv.setOriginalFilename(re.getFilePojo().getName());
		cv.setFilepath(JSONObject.toJSONString(re.getFilePojo()));
		cv.setCvInfo(re.getOriginal());
		cv.setCvDate(dateFormate2(re.getLastUpdate())); // 201606
		cv.setTopexpsallay(getMaxSallary(re.getAimSalary()));
		cv.setIntegrity(Integer.parseInt(re.getIntegrity()));
		cv.setSource(3);
		cv.setFlag(0);
		ao.setCv(cv);
	}

	private static BigDecimal getMaxSallary(String sallary) {
		if (sallary != null) {
			Integer tmp = 0;
			Pattern p = Pattern.compile("[0-9]+");
			Matcher m = p.matcher(sallary);
			if (sallary.indexOf("年") != -1) {

				while (m.find()) {
					sallary = m.group();
					if (tmp < Integer.parseInt(sallary)) {
						tmp = Integer.parseInt(sallary);
					}
				}
				if (tmp != null && tmp != 0)
					return new BigDecimal(((float) tmp) / 12).setScale(2, BigDecimal.ROUND_HALF_UP);

			} else {
				while (m.find()) {
					sallary = m.group();
					if (tmp < Integer.parseInt(sallary)) {
						tmp = Integer.parseInt(sallary);
					}
				}
				if (tmp != null && tmp != 0)
					return new BigDecimal(tmp);
			}

		}
		return null;
	}

	@Test
	public void test02() {
		System.out.println(new BigDecimal(10000d / 3));
		System.out.println(new BigDecimal(10000f / 3));
		System.out.println(((double) 10) / 3);
		System.out.println(getMaxSallary("200000-300001元/年"));
		System.out.println(getMaxSallary("200000-300001元/月"));
	}

	private static String getUid(String path) {
		if (path != null) {
			Pattern p = Pattern.compile("[0-9]{7,}");
			Matcher m = p.matcher(path);
			if (m.find()) {
				path = m.group();
			}
		}
		return null;
	}

	/**
	 * 日期格式转换 2016/06
	 * 
	 * @param time
	 * @return
	 */
	private static Date dateFormate(String time) {
		if (time != null) {
			try {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Pattern p = Pattern.compile("([0-9]{4})[^0-9]+([0-9]{2})");
				Matcher m = p.matcher(time);
				if (m.find()) {
					if (m.groupCount() == 2) {
						String year = m.group(1);
						String month = m.group(2);
						return sdf.parse(year + "-" + month + "-00");
					}
				} else if (time.indexOf("至今") != -1) {
					return new Date();
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 日期格式转换 201606
	 * 
	 * @param time
	 * @return
	 */
	private static Date dateFormate2(String time) {
		if (time != null) {
			if (time.length() >= 6) {
				time = time.substring(0, 4) + "-" + time.substring(4, 6);
			} else {
				return null;
			}
			try {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Pattern p = Pattern.compile("([0-9]{4})[^0-9]+([0-9]{2})");
				Matcher m = p.matcher(time);
				if (m.find()) {
					if (m.groupCount() == 2) {
						String year = m.group(1);
						String month = m.group(2);
						return sdf.parse(year + "-" + month + "-00");
					}
				} else if (time.indexOf("至今") != -1) {
					return new Date();
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Test
	public void test() {
		String str = "2015-03dada";
		System.out.println(dateFormate(str));
	}

	private static void transBasic(ResumeInfo re, AngelObject ao) {
		ACvBasic bn = new ACvBasic();
		bn.setUid(ao.getUid());
		bn.setResumegrade(re.getResumeGrade());
		if (re.getMarried() != null && !re.getMarried().equals(""))
			bn.setMarriage(getMarrinum(re.getMarried()));
		bn.setFromwebsite(re.getFromWebSite());
		bn.setWebsiteresumeid(re.getWebSiteResumeID());
		bn.setKeyword(re.getKeyword());
		bn.setIdcard(re.getIDNO());
		bn.setEncouragement(re.getEncouragement());
		bn.setTeam(re.getTeam());
		bn.setWorkYear(dateFormate(re.getBeginworktime()));// 2000-09
		bn.setCertificate(re.getCertificate());
		bn.setComment(re.getPersonal());
		// bn.set English // 外语水平（ 并不特指英语）
		bn.setSchool(re.getSchool());// 排名 学校类型
		bn.setSchoolrankings(re.getSchoolRankings());
		bn.setSchooltype(re.getSchoolType());
		bn.setMajor(re.getSpeciality());
		bn.setAddress(re.getAddress());
		bn.setBirthPlace(re.getJiguan());// 籍贯
		bn.setCountry(re.getNationality());// 国籍
		bn.setNationality(re.getNational()); // 民族
		bn.setBirthday(re.getBirth());
		bn.setName(re.getName());
		bn.setHref(re.getHref());// 个人主页
		bn.setTitlestandard(re.getTitleStandard());
		bn.setAiminstitution(re.getAimInstitution());// 应聘机构（招聘网站发布的公司名称）
		bn.setAge(re.getAge());
		if (re.getSex() != null && !re.getSex().equals(""))
			bn.setGender(getGender(re.getSex()));
		bn.setHeight(re.getHigh()); // 身高（例如： 185cm）
		bn.setWeight(re.getWeight());//
		bn.setMobile(re.getMobile());
		bn.setPhone(re.getPhone());
		bn.setFax(re.getFax());
		bn.setEmail(re.getEmail());
		bn.setCity(re.getNowLocation()); // 设置城市
		bn.setEducation(re.getEducation());// 最高学历
		if (re.getAdvancedDegree() != null && !re.getAdvancedDegree().equals("")) {
			bn.setDegree(getDegreeNum(re.getAdvancedDegree())); // 学位
			bn.setEducation(re.getAdvancedDegree());
		} else if (re.getEducation() != null && !re.getEducation().equals("")) {
			bn.setDegree(getDegreeNum(re.getEducation())); // 学历
			bn.setEducation(re.getEducation());
		}
		if (re.getExperience() != null && !re.getExperience().equals("")) {
			bn.setJobTime(Integer.parseInt(re.getExperience()));
		}
		bn.setTrade(re.getVocation());
		bn.setVocationstandard(re.getVocationStandard());
		bn.setPolitics(re.getPolitical());
		bn.setStartfrom(re.getStartFrom());// 到岗时间
		bn.setQq(re.getQQ());
		bn.setStudenttype(re.getStudentType());
		bn.setPhotoUrl(re.getPhotoUrl());
		bn.setAppletter(re.getAppLetter());
		bn.setCompany(re.getLastCompany());
		bn.setTitle(re.getLastTitle());
		bn.setOverseaswork(re.getOverseasWork());
		bn.setJobhoppingfrequency(re.getJobHoppingFrequency());
		bn.setWorktype(re.getWorkType());
		bn.setMemo(re.getMemo());
		if (re.getGradeOfEnglish() != null && !re.getGradeOfEnglish().equals(""))
			bn.setGradeofenglish(JSONObject.toJSONString(re.getGradeOfEnglish()));
		if (re.getLanguagesSkills() != null && !re.getLanguagesSkills().equals(""))
			bn.setLanguagesskills(JSONObject.toJSONString(re.getLanguagesSkills()));
		if (re.getTrainingInfo() != null && !re.getTrainingInfo().equals(""))
			bn.setTraininginfo(JSONObject.toJSONString(re.getTrainingInfo()));
		bn.setFlag(0);
		// 解析省市区
		parseProCiDi(bn);
		ao.setBasic(bn);
	}

	/**
	 * <p>
	 * 解析省、市、区
	 * </p>
	 * 
	 * @param basic
	 */
	private static void parseProCiDi(ACvBasic basic) {
		String pcd = basic.getCity();
		if (pcd != null && !pcd.equals("")) {
			basic.setProvince(getPcd(pcd, provinces));
			basic.setCity(getPcd(pcd, citys));
			basic.setDistricts(getPcd(pcd, districts));
		}

	}

	private static String getPcd(String pcd, List<String> pcdlist) {
		// TODO Auto-generated method stub
		for (int i = 0; i < pcdlist.size(); i++) {
			if (pcd.indexOf(pcdlist.get(i)) != -1) {
				if (pcdlist.get(i).length() > 1)
					return pcdlist.get(i);
			}
		}
		return null;
	}

	private static Integer getGender(String sex) {
		if (sex.indexOf("男") != -1) {
			return 1;
		} else if (sex.indexOf("女") != -1) {
			return 2;
		}
		return null;
	}

	/**
	 * @desc 0未知，1未婚，2已婚，3已育，4离异，5丧偶，6其他
	 * @param married
	 * @return
	 */
	private static int getMarrinum(String married) {
		if (married.indexOf("未婚") != -1) {
			return 1;
		} else if (married.indexOf("已婚") != -1) {
			return 2;
		} else if (married.indexOf("已育") != -1) {
			return 3;
		} else if (married.indexOf("离异") != -1) {
			return 4;
		} else if (married.indexOf("丧偶") != -1) {
			return 5;
		} else if (married.indexOf("其他") != -1) {
			return 6;
		}
		return 6;
	}

	private static String getDegreeNum(String degree) {

		if (degree.contains("小学")) {
			return "0";
		} else if (degree.contains("初中")) {
			return "1";
		} else if (degree.contains("高中") || degree.contains("中技") || degree.contains("技校") || degree.contains("中专")) {
			return "2";
		} else if (degree.contains("专科") || degree.contains("大专")) {
			return "3";
		} else if (degree.contains("本科") || degree.contains("学士") || degree.contains("大学")) {
			return "4";
		} else if (degree.contains("硕士") || degree.contains("研究生") || degree.contains("MBA")
				|| degree.contains("EMBA")) {
			return "5";
		} else if (degree.contains("博士")) {
			return "6";
		} else if (degree.contains("博士后")) {
			return "7";
		}
		return null;
	}

	private static void transEdu(ResumeInfo resume, AngelObject ao) {
		EducationInfo[] educationInfos = resume.getEducationInfo();
		if (educationInfos != null) {
			List<ACvEducation> educations = new ArrayList<ACvEducation>();
			for (EducationInfo education : educationInfos) {
				ACvEducation edu = new ACvEducation();
				edu.setUid(ao.getUid());
				edu.setStartTime(dateFormate(education.getStartDate()));
				edu.setEndTime(dateFormate(education.getEndDate()));
				edu.setSchool(education.getSchool());
				edu.setMajor(education.getSpeciality());
				if (education.getEducation() != null && !education.getEducation().equals("")) {
					edu.setDegree(Integer.parseInt(getDegreeNum(education.getEducation())));
					edu.setEducation(education.getEducation());
				}

				edu.setDepartment(education.getDepartment());
				edu.setIsstudii(education.getIsStudii());
				edu.setInfo(education.getSummary());
				edu.setFlag(0);
				educations.add(edu);
			}
			ao.setEdus(educations);
		}

	}

	/**
	 * 期望信息
	 * 
	 * @param resume
	 * @param cv
	 */
	private static void transExp(ResumeInfo resume, AngelObject cv) {
		// Forwardlocation、ForwardVocation、AimSalary
		ACvExpectation exp = new ACvExpectation();
		exp.setUid(cv.getUid());
		exp.setExpTitle(resume.getTitle());
		exp.setExpCity(resume.getForwardlocation());
		exp.setExpTrade(resume.getForwardVocation());
		if (resume.getAimSalary() != null && !resume.getAimSalary().equals("")) {
			dealWithExpSal(exp, resume.getAimSalary());
		}
		exp.setCurSalary(getMaxSallary(resume.getSalary()));
		// 工作状态
		exp.setJobStatus(resume.getSwitch());// 是否处于找工作状态

		exp.setFlag(0);
		cv.setExp(exp);

	}

	private static void dealWithExpSal(ACvExpectation cvExp, String expSalary) {
		Pattern p = Pattern.compile("\\d+");
		Matcher m = p.matcher(expSalary);
		int i = 0;
		
		if(expSalary.indexOf("年")!=-1){
			while (m.find()) {
				if (0 == i) {
					cvExp.setExpLowsalary(new BigDecimal(Float.parseFloat(m.group())/12).setScale(2, BigDecimal.ROUND_HALF_UP));
				} else if (1 == i) {
					String topSa = m.group();
					int topS = Integer.parseInt(topSa);
					if (topS > Integer.parseInt(cvExp.getExpLowsalary() + "")) {
						cvExp.setExpTopsalary(new BigDecimal(Float.parseFloat(topSa)/12).setScale(2, BigDecimal.ROUND_HALF_UP));
					}
				}
				i++;
			}
		}else{
			while (m.find()) {
				if (0 == i) {
					cvExp.setExpLowsalary(new BigDecimal(m.group()));
				} else if (1 == i) {
					String topSa = m.group();
					int topS = Integer.parseInt(topSa);
					if (topS > Integer.parseInt(cvExp.getExpLowsalary() + "")) {
						cvExp.setExpTopsalary(new BigDecimal(topSa));
					}
				}
				i++;
			}
		} 
	}

	private static void transJob(ResumeInfo resume, AngelObject cv) {
		ExperienceInfo[] experienceInfos = resume.getExperienceInfo();
		if (experienceInfos != null) {
			List<ACvJob> jobs = new ArrayList<ACvJob>();
			for (ExperienceInfo exper : experienceInfos) {
				ACvJob job = new ACvJob();
				job.setUid(cv.getUid());
				job.setStartTime(dateFormate(exper.getStartDate()));
				job.setEndTime(dateFormate(exper.getEndDate()));
				job.setCompany(exper.getCompany());
				job.setCity(exper.getLocation());
				job.setTrade(exper.getVocation());
				if (exper.getSize() != null && !exper.getSize().equals(""))
					job.setCompanysize(exper.getSize().replace("人", "")); 
				job.setCompanynature(exper.getType());
				job.setDepartment(exper.getDepartment());
				job.setTitle(exper.getTitle());
				if (getMaxSallary(exper.getSalary()) != null)
					job.setSalary(getMaxSallary(exper.getSalary()) + "");
				job.setReport(exper.getLeader());
				if (exper.getUnderlingNumber() != null && !exper.getUnderlingNumber().equals("")
						&& !exper.getUnderlingNumber().equals("0"))
					job.setMember(exper.getUnderlingNumber().replace("人", ""));// 下属人数
				job.setReason(exper.getReasonOfLeaving());
				job.setInfo(exper.getSummary());// 详细介绍
				job.setFlag(0);
				jobs.add(job);
			}
			cv.setJobs(jobs);
		}

	}

	private static void transPro(ResumeInfo resume, AngelObject cv) {
		ProjectInfo[] projectInfos = resume.getProjectInfo();
		if (projectInfos != null) {
			List<ACvProject> pros = new ArrayList<ACvProject>();
			for (ProjectInfo project : projectInfos) {
				ACvProject pro = new ACvProject();
				pro.setUid(cv.getUid());
				pro.setStartTime(dateFormate(project.getStartDate()));
				pro.setEndTime(dateFormate(project.getEndDate()));
				pro.setProjectName(project.getProjectName());
				pro.setTitle(project.getTitle());// 项目职务
				pro.setContent(project.getProjectDescription());
				pro.setDuty(project.getResponsibilities());
				pro.setFlag(0);
				pros.add(pro);
			}
			cv.setPros(pros);
		}

	}

	/**
	 * <p>
	 * 获取技能信息
	 * </p>
	 * 
	 * @param resume
	 * @param cv
	 */
	private static void transSkill(ResumeInfo resume, AngelObject cv) {
		ITSkills[] skills = resume.getITSkills();
		if (skills != null) {
			List<ACvSkill> sks = new ArrayList<ACvSkill>();
			for (ITSkills skill : skills) {
				ACvSkill sk = new ACvSkill();
				sk.setUid(cv.getUid());
				sk.setSkillname(skill.getSkillType());
				sk.setLevel(skill.getCompetencyLevel());
				if (skill.getTimeOfUse() != null && !skill.getTimeOfUse().equals("")) {
					Pattern p = Pattern.compile("[0-9]+");
					Matcher m = p.matcher(skill.getTimeOfUse());
					if (m.find()) {
						sk.setMonth(Integer.parseInt(m.group()));
					}
				}
				sk.setFlag(0);
				sks.add(sk);

			}
			cv.setSkills(sks);
		}

	}

}
